﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CBMS.Common;
using CBMS.Interfaces;
using CBMS.Business;
using CBMS.Models;
using CBMS.Resources;
using CBMS.Objects;
namespace CBMS.View
{
    public partial class frmStaffDetail : frmBase
    {
        #region Fields
        public Boolean _IsEditProfile = false;
        public static ISubCategoryRepository subRep { get; set; }
        public static IStaffRepository staffRep { get; set; }
        private string strError = string.Empty;
        private int _staffId = 0;
        #endregion

        #region Init,Load
        public frmStaffDetail()
        {
            InitializeComponent();
            staffRep = new StaffRepository();
        }
        public frmStaffDetail(int staffId)
        {
            _staffId = staffId;
            InitializeComponent();
            staffRep = new StaffRepository();
        }
        public frmStaffDetail(Boolean isEditProfile)
        {
            _IsEditProfile = isEditProfile;
            InitializeComponent();
            staffRep = new StaffRepository();
        }
        private void frmStaffDetail_Load(object sender, EventArgs e)
        {
            InitControl();
            if (!_IsEditProfile)
            {
                if (_staffId > 0)
                {
                    this.Text = "Edit staff";
                    LoadData();
                }
                else this.Text = "Insert staff";
            }
            else
            {
                this.Text = "Edit profile";
                _staffId = this.userLoginId;
                LoadData();
            }
            cmbPosition.Focus();
        }
        #endregion

        #region Method
        private void UpdateStaff(Staff objStaff, List<AbilityOfStaff> lstAbility)
        {
            int result = staffRep.Update(objStaff, lstAbility);
            if (result == 1)
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else if (result == -1)//code duplicate
            {
                MessageBox.Show(string.Format(Resources.ErrorMessages.E0005, BaseFunctions.Removetext(lblCode.Text)), ErrorMessages.T001, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (result == -2)//user name duplicate
            {
                MessageBox.Show(string.Format(Resources.ErrorMessages.E0005, BaseFunctions.Removetext(lblUserName.Text)), ErrorMessages.T001, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (result == -3)//email duplicate
            {
                MessageBox.Show(string.Format(Resources.ErrorMessages.E0005, BaseFunctions.Removetext(lblEmail.Text)), ErrorMessages.T001, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (result == 0)//eeror
            {
                MessageBox.Show(string.Format(ErrorMessages.I0003, "Update"), ErrorMessages.T002, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void InsertStaff(Staff objStaff, List<AbilityOfStaff> lstAbility)
        {
            int result = staffRep.Insert(objStaff, lstAbility);
            if (result > 0)
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else if (result == -1)//code duplicate
            {
                MessageBox.Show(string.Format(Resources.ErrorMessages.E0005, BaseFunctions.Removetext(lblCode.Text)), ErrorMessages.T001, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (result == -2)//user name duplicate
            {
                MessageBox.Show(string.Format(Resources.ErrorMessages.E0005, BaseFunctions.Removetext(lblUserName.Text)), ErrorMessages.T001, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (result == -3)//email duplicate
            {
                MessageBox.Show(string.Format(Resources.ErrorMessages.E0005, BaseFunctions.Removetext(lblEmail.Text)), ErrorMessages.T001, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (result == 0)//eeror
            {
                MessageBox.Show(string.Format(ErrorMessages.I0003, "Insert"), ErrorMessages.T002, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void LoadData()
        {
            Staff objStaff = staffRep.GetByID(_staffId);
            if (objStaff != null)
            {
                txtCode.Text = objStaff.staff_code.Trim();
                if (!objStaff.is_active.HasValue)
                    chkIsActive.Checked = false;
                else chkIsActive.Checked = objStaff.is_active.Value;
                cmbPosition.SelectedValue = objStaff.role_code;
                if (objStaff.branch_id.HasValue)
                    cmbBranch.SelectedValue = objStaff.branch_id.Value.ToString();
                txtFirstName.Text = objStaff.first_name;
                txtLastName.Text = objStaff.last_name;
                txtUserName.Text = objStaff.user_name;
                txtUserName.Enabled = false;
                txtPassword.Text = objStaff.password;
                txtPassword.Enabled = false;
                txtEmail.Text = objStaff.email;
                txtPhone.Text = objStaff.phone;
                txtDateOfBirth.Value = objStaff.birthday.Value;
                if (objStaff.country_code != null)
                    cmbCountry.SelectedValue = objStaff.country_code;
                if (objStaff.state_code != null)
                    cmbState.SelectedValue = objStaff.state_code;
                txtSuburb.Text = objStaff.suburb;
                txtZipCode.Text = objStaff.zip;
                txtRate.Text = objStaff.rate.ToString();
                txtAddress.Text = objStaff.address;
                //bind list ability              
                CheckAbilityItem();
                if (_staffId == this.userLoginId)
                    chkIsActive.Enabled = false;
            }
        }
        private void CheckAbilityItem()
        {
            IList<AbilityOfStaff> lstAbility = staffRep.GetAbilityOfStaff(_staffId);
            foreach (AbilityOfStaff objAbility in lstAbility)
            {
                int i = 0;
                foreach (ItemDTO checkedItem in clbAbility.Items)
                {
                    if (objAbility.subcategory_id == checkedItem.Id)
                    {
                        clbAbility.SetItemChecked(i, true);
                        break;
                    }
                    i++;
                }
            }
        }
        private void InitControl()
        {
            CommonFunction.MakeCheckBoxAbility(BaseFunctions.STAFF_ABILITY, clbAbility);
            CommonFunction.MakeComboBoxRole(cmbPosition, true);
            CommonFunction.MakeComboBoxBranch(cmbBranch, true);
            CommonFunction.MakeComboBoxCountry(cmbCountry, true);
        }
        private void ClearForm()
        {
            chkIsActive.Checked = false;
            cmbPosition.SelectedValue = string.Empty;
            cmbBranch.SelectedValue = string.Empty;
            txtFirstName.Text = string.Empty;
            txtLastName.Text = string.Empty;
            txtUserName.Text = string.Empty;
            txtPassword.Text = string.Empty;
            txtPhone.Text = string.Empty;
            txtDateOfBirth.Text = string.Empty;
            cmbCountry.SelectedValue = string.Empty;
            cmbState.SelectedValue = string.Empty;
            txtSuburb.Text = string.Empty;
            txtZipCode.Text = string.Empty;
            txtAddress.Text = string.Empty;
            txtAbilityName.Text = string.Empty;
        }
        private bool CheckValidationForm()
        {
            bool result = true;
            Control txt = new Control();
            Control ctrFocus = new Control();
            string strNameText = string.Empty;
            string strAsign = "erro";
            string strErr = ErrorMessages.E0001;
            this.strError = string.Empty;
            if (cmbPosition.SelectedIndex == 0)
            {
                if (strNameText == string.Empty)
                {
                    strNameText = strAsign;
                    txt = (Control)cmbPosition;
                }
                ctrFocus = (Control)cmbPosition;
                this.strError += string.Format(ErrorMessages.E0002, BaseFunctions.Removetext(lblPosition.Text)) + "\r\n";
                result = false;

            }
            if (cmbPosition.SelectedValue.ToString() == BaseFunctions.ROLES_MANAGER || cmbPosition.SelectedValue.ToString() == BaseFunctions.ROLES_RCEPTIONIST)
            {
                if (cmbBranch.SelectedValue.ToString() == string.Empty)
                {
                    strNameText = strAsign;
                    txt = (Control)cmbBranch;
                    this.strError += string.Format(strErr, BaseFunctions.Removetext(lblBranch.Text)) + "\r\n";
                    if (result)
                    {
                        ctrFocus = (Control)cmbBranch;
                        result = false;
                    }
                }
            }
            if (txtFirstName.Text.Trim() == string.Empty)
            {
                strNameText = strAsign;
                txt = (Control)txtFirstName;
                this.strError += string.Format(ErrorMessages.E0001, BaseFunctions.Removetext(lblFirstName.Text)) + "\r\n";
                if (result)
                {
                    ctrFocus = (Control)txtFirstName;
                    result = false;
                }
            }
            if (txtLastName.Text.Trim() == string.Empty)
            {
                strNameText = strAsign;
                txt = (Control)txtLastName;
                this.strError += string.Format(ErrorMessages.E0001, BaseFunctions.Removetext(lblLastName.Text)) + "\r\n";
                if (result)
                {
                    ctrFocus = (Control)txtLastName;
                    result = false;
                }
            }
            if (txtUserName.Text.Trim() != string.Empty && !BaseFunctions.IsValidAccount(txtUserName.Text.Trim()))
            {
                if (strNameText == string.Empty)
                {
                    strNameText = strAsign;
                    txt = (Control)txtUserName;
                }
                this.strError += string.Format(ErrorMessages.E0003, BaseFunctions.Removetext(lblUserName.Text)) + "\r\n";
                if (result)
                {
                    ctrFocus = (Control)txtUserName;
                    result = false;
                }
            }
            if (txtRate.Text.Trim() != string.Empty && !BaseFunctions.ValidateNumber(txtRate.Text.Trim()))
            {
                if (strNameText == string.Empty)
                {
                    strNameText = strAsign;
                    txt = (Control)txtRate;
                }
                this.strError += string.Format(ErrorMessages.E0003, BaseFunctions.Removetext(lblRate.Text)) + "\r\n";
                if (result)
                {
                    ctrFocus = (Control)txtRate;
                    result = false;
                }
            }
            //set focus at postition first error
            BaseFunctions.SetFocusWhenError(ctrFocus, result, strNameText);
            return result;
        }
        #endregion

        #region Events
        private void cmbPosition_SelectedIndexChanged(object sender, EventArgs e)
        {
            string type = cmbPosition.SelectedValue.ToString();
            if (type == BaseFunctions.ROLES_THERAPIST)
            {
                cmbBranch.SelectedIndex = 0;
                cmbBranch.Enabled = false;
            }
            else
            {
                cmbBranch.Enabled = true;
            }
        }
        private void btnAddAbility_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtAbilityName.Text))
            {

                Control txt = new Control();
                string strNameText = string.Empty;
                string strAsign = "erro";
                string strErr = ErrorMessages.E0001;
                this.strError = string.Empty;
                strNameText = strAsign;
                txt = (Control)txtAbilityName;
                this.strError += string.Format(strErr, "Ability") + "\r\n";
                //set focus at postition first error
                BaseFunctions.SetFocusWhenError(txt, false, strNameText);
                MessageBox.Show(this.strError, ErrorMessages.T001, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                try
                {
                    subRep = new SubCategoryRepository();
                    SubCategory objSubCate = new SubCategory();
                    objSubCate.category_id = BaseFunctions.STAFF_ABILITY;
                    objSubCate.subcategory_name = txtAbilityName.Text;
                    objSubCate.created_by = this.userLogin;
                    objSubCate.created_date = CommonFunction.Now;
                    subRep.Add(objSubCate);
                    subRep.SaveChanges();
                    CommonFunction.MakeCheckBoxMaster(BaseFunctions.STAFF_ABILITY, clbAbility);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, ErrorMessages.T001, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        private void cmbCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            string country = cmbCountry.SelectedValue.ToString();
            CommonFunction.MakeComboBoxState(cmbState, country, true);
            if (country == BaseFunctions.COUNTRY_Australia)
            {
                cmbState.Enabled = true;
            }
            else
            {

                cmbState.Enabled = false;
            }
        }
        private Staff GetObjectStaff()
        {
            Staff objStaff = new Staff();
            if (this._staffId > 0)
            {
                objStaff = staffRep.GetByID(this._staffId);
            }
            objStaff.staff_code = txtCode.Text.Trim();
            objStaff.is_active = chkIsActive.Checked;
            objStaff.role_code = cmbPosition.SelectedValue.ToString();
            if (cmbBranch.SelectedValue.ToString() != string.Empty)
            {
                objStaff.branch_id = int.Parse(cmbBranch.SelectedValue.ToString());
            }
            objStaff.first_name = txtFirstName.Text.Trim();
            objStaff.last_name = txtLastName.Text.Trim();
            objStaff.user_name = txtUserName.Text.Trim();
            objStaff.password = BaseFunctions.Encrypte(txtPassword.Text.Trim());
            objStaff.email = txtEmail.Text.Trim();
            objStaff.phone = txtPhone.Text.Trim();
            objStaff.birthday = txtDateOfBirth.Value;
            objStaff.country_code = cmbCountry.SelectedValue.ToString();
            objStaff.state_code = cmbState.SelectedValue.ToString();
            objStaff.suburb = txtSuburb.Text.Trim();
            objStaff.zip = txtZipCode.Text.Trim();
            objStaff.address = txtAddress.Text;
            if (txtRate.Text != string.Empty)
                objStaff.rate = double.Parse(txtRate.Text);
            if (this._staffId == 0)
            {
                objStaff.created_by = this.userLogin;
                objStaff.created_date = CommonFunction.Now;
            }
            objStaff.modified_by = this.userLogin;
            objStaff.modified_date = CommonFunction.Now;
            return objStaff;

        }
        private List<AbilityOfStaff> GetListAbility()
        {
            List<AbilityOfStaff> lstSubCate = new List<AbilityOfStaff>();
            foreach (ItemDTO checkedItem in clbAbility.CheckedItems)
            {
                AbilityOfStaff objCate = new AbilityOfStaff();
                objCate.subcategory_id = checkedItem.Id;
                lstSubCate.Add(objCate);
            }
            return lstSubCate;
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!CheckValidationForm())
            {
                MessageBox.Show(this.strError, ErrorMessages.T001, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                List<AbilityOfStaff> lstAbility = GetListAbility();
                var objStaff = GetObjectStaff();
                if (this._staffId < 1)
                    InsertStaff(objStaff, lstAbility);
                else
                {
                    objStaff.staff_id = _staffId;
                    UpdateStaff(objStaff, lstAbility);
                }
            }
        }
        private void btnClear_Click(object sender, EventArgs e)
        {
            if (_staffId > 0)
                LoadData();
            else ClearForm();
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void txtAbilityName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                btnAddAbility_Click(null, null);
            }
        }
        #endregion
    }
}
